<script setup lang="ts">
import type { ReportColumnsItem } from './types'

const props = defineProps<{
  columns: ReportColumnsItem[]
  showLineNumber?: boolean
}>()

const rowCount = computed<number>(() => {
  const columns = props.columns
  // 获取children层级
  const getTreeLevel = (arr: ReportColumnsItem[]) => {
    let maxLevel = 0;
    (function callBack(arr, level) {
      ++level
      maxLevel = Math.max(level, maxLevel)
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        if (item && item.children && item.children.length > 0) {
          callBack(item.children, level)
        }
      }
    })(arr, maxLevel)
    return maxLevel
  }
  return getTreeLevel(columns)
})

// 获取表头某一层
function getColumnsByLevel(x = 1) {
  const columns = props.columns
  const count = rowCount.value
  const getChildrenLength = (children: any[]) => {
    if (children.every(child => !child.children || child.children.length === 0)) {
      return children.length
    }
    return children.reduce((acc, v) => {
      if (v.children) {
        acc += getChildrenLength(v.children)
      }
      else {
        acc += 1
      }
      return acc
    }, 0)
  }
  const getColumns = (arr: ReportColumnsItem[]) => {
    const result = []
    let level = 0;
    (function callback(arr) {
      level++
      for (let i = 0; i < arr.length; i++) {
        const v = arr[i]
        if (v) {
          const { children, ...rest } = v
          if (level === x) {
            const obj = { ...rest }

            // 计算当前单元格的 colspan 和 rowspan 属性值
            if (children && children.length > 0) {
              obj.colspan = getChildrenLength(children)
              obj.rowspan = 1
            }
            else {
              obj.rowspan = count - x + 1
              obj.colspan = 1
            }

            if (!obj.hidden) {
              result.push(obj)
            }
          }
          else if (children && children.length > 0) {
            callback(children)
            level--
          }
        }
      }
    })(arr)
    return result
  }
  return getColumns(columns)
}
</script>

<template>
  <thead>
    <tr v-for="row in rowCount" :key="row">
      <th
        v-if="showLineNumber && row === 1"
        :rowspan="rowCount"
        class="readonly width-40px"
      >
        行
      </th>
      <th
        v-for="column in getColumnsByLevel(row)"
        :key="column.prop"
        :rowspan="column.rowspan"
        :colspan="column.colspan"
        :style="column.width ? `width:${column.width}px` : ''"
      >
        <div class="table-cell">
          {{ column.label }}
          <small v-if="column.unit">（{{ column.unit }}）</small>
        </div>
      </th>
    </tr>
  </thead>
</template>
